﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PersonalWebSite.Common.DTO;
using PersonalWebSite.Models.Admin;
using System.Web.Mvc;
using log4net;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Globalization;

namespace PersonalWebSite.Common
{
    /// <summary>
    /// Defines the FileDataManager
    /// </summary>
    public class FileDataManager
    {
        #region Variables
        private static readonly string baseDataPath = null;
        private static readonly Regex dateTimeRegEx = null;
        private static readonly string dateTimeFormat = null;

        private static readonly ILog logger = LogManager.GetLogger(typeof(FileDataManager));
        #endregion

        #region Constructor
        /// <summary>
        /// Inits the class
        /// </summary>
        static FileDataManager()
        {
            log4net.Config.XmlConfigurator.Configure();

            baseDataPath = HttpContext.Current.Server.MapPath("~/Data");
            dateTimeRegEx = new Regex("\"\\d{4}-\\d{2}-\\d{2}.\\d{2}:\\d{2}:\\d{2}\"");
            dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
        }
        #endregion

        /// <summary>
        /// Saves the given file info
        /// </summary>
        /// <param name="model">file info</param>
        /// <returns>Processing result</returns>
        public static ProcessingResult SaveFileInfo(FileInfoViewModel model)
        {
            if (model == null)
            {
                return new ProcessingResult
                {
                    IsSuccess = false,
                    UserFriendlyMessage = "The given File Info is empty!",
                    DetailsMessage = "The given FileInfoViewModel object is null"
                };
            }

            try
            {
                using (StreamWriter streamWriter = new StreamWriter(baseDataPath + "/" + model.FileName))
                {
                    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                    model.Content = dateTimeRegEx.Replace(model.Content, match => javaScriptSerializer.Serialize(DateTime.ParseExact(match.Value.Replace("\"", string.Empty), dateTimeFormat, CultureInfo.CurrentCulture)));
                    streamWriter.Write(model.Content);
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("An error occured while trying to save the data file \"{0}\"", model.FileName);
                logger.Error(message, ex);
                return new ProcessingResult { 
                    IsSuccess = false,
                    UserFriendlyMessage = message,
                    DetailsMessage = ex.Message
                };
            }

            return new ProcessingResult
            {
                IsSuccess = true,
                UserFriendlyMessage = string.Format("File \"{0}\" has successfully been saved!", model.FileName)
            };
        }

        /// <summary>
        /// Loads the given file content
        /// </summary>
        /// <param name="fileName">fileName</param>
        /// <returns>FileInfoViewModel</returns>
        public static FileInfoViewModel LoadFileInfo(string fileName)
        {
            try
            {
                using (StreamReader streamReader = new StreamReader(baseDataPath + "/" + fileName))
                {
                    return new FileInfoViewModel
                    {
                        FileName = fileName,
                        Content = streamReader.ReadToEnd()
                    };
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("An error occured while trying to load the data file \"{0}\"", fileName);
                logger.Error(message, ex);
                return new FileInfoViewModel
                {
                    FileName = fileName
                };
            }
        }
    }
}